package cn.cttic.link.dubbo;

import cn.cttic.base.api.RemoteBaseDeviceInfoService;
import cn.cttic.common.core.domain.R;
import cn.cttic.common.core.exception.link.LinkException;
import cn.cttic.link.api.RemoteThirdMagooService;
import cn.cttic.link.api.domain.BaseThirdInterfaceConfig;
import cn.cttic.link.api.domain.bo.BaseThirdInterfaceBo;
import cn.cttic.link.api.domain.vo.*;
import cn.cttic.link.api.enums.ThirdInterfaceType;
import cn.cttic.link.service.IBaseThirdInterfaceConfigService;
import cn.cttic.link.service.IBaseThirdInterfaceService;
import cn.cttic.link.util.HttpClientUtil;
import cn.cttic.order.api.RemoteInstallOrderService;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
@DubboService
public class RemoteThirdMagooServiceImpl implements RemoteThirdMagooService {

    private final IBaseThirdInterfaceConfigService baseThirdInterfaceConfigService;

    private final IBaseThirdInterfaceService thirdInterfaceService;

    @DubboReference
    private RemoteBaseDeviceInfoService remoteBaseDeviceInfoService;

    @DubboReference
    private RemoteInstallOrderService remoteInstallOrderService;

    /**
     * 设备终端数据同步接口
     *
     * @param imei IMEI 号码
     * @return 结果
     */
    @Override
    public boolean checkTerminalInfo(String orderId, String imei) {

        try {
            log.info("[麦谷接口][设备终端数据同步接口][开始]");
            BaseThirdInterfaceConfigVo config = baseThirdInterfaceConfigService.getInterfaceConfig(ThirdInterfaceType.MAPGOO_SYNC_TERMINAL_DATA.getValue());

            String url = config.getAccessUrl();
            log.info("[麦谷接口][设备终端数据同步接口][请求地址]: {}", url);

            Map<String, Object> params = new HashMap<>();
            params.put("terminalId", imei);
            params.put("cameraNumber", 2);
            params.put("createTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            params.put("command", 1);
            log.info("[麦谷接口][设备终端数据同步接口][请求内容]: {}", JSON.toJSONString(params));

            String result = HttpClientUtil.post(url, JSON.toJSONString(params), false);
            log.info("[麦谷接口][设备终端数据同步接口][返回内容]: {}", result);

            BaseThirdInterfaceBo interfaceBo = new BaseThirdInterfaceBo();
            interfaceBo.setBusinessId(orderId);
            interfaceBo.setInterfaceType(ThirdInterfaceType.MAPGOO_SYNC_TERMINAL_DATA.getValue());
            interfaceBo.setAccessUrl(url);
            interfaceBo.setRequestType("POST");
            interfaceBo.setRequestBody(JSON.toJSONString(params));
            interfaceBo.setResponseBody(result);

            if (!thirdInterfaceService.insertByBo(interfaceBo)) {
                throw new LinkException("录入接口数据失败");
            }
            log.info("[麦谷接口][设备终端数据同步接口][保存记录完成]");

            ThirdMapgooR r = JSON.parseObject(result, ThirdMapgooR.class);
            if (r.isSuccess() || r.getCode() == ThirdMapgooR.SUCCESS) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            throw new LinkException(e.getMessage());
        }
    }

    /**
     * 查询终端注册结果
     *
     * @param imei IMEI 号码
     * @return 结果
     */
    @Override
    public boolean registerTerminal(String orderId, String imei) {

        try {
            log.info("[麦谷接口][查询终端注册结果][开始]");
            BaseThirdInterfaceConfigVo config = baseThirdInterfaceConfigService.getInterfaceConfig(ThirdInterfaceType.MAPGOO_QUERY_TERMINAL_REGISTER.getValue());

            String url = config.getAccessUrl();
            log.info("[麦谷接口][查询终端注册结果][请求地址]: {}", url);

            Map<String, Object> params = new HashMap<>();
            params.put("terminalId", imei);
            params.put("cameraNumber", 2);
            params.put("createTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            params.put("command", 1);
            log.info("[麦谷接口][查询终端注册结果][请求内容]: {}", JSON.toJSONString(params));

            String result = HttpClientUtil.post(url, JSON.toJSONString(params), false);
            log.info("[麦谷接口][查询终端注册结果][返回内容]: {}", result);

            BaseThirdInterfaceBo interfaceBo = new BaseThirdInterfaceBo();
            interfaceBo.setBusinessId(orderId);
            interfaceBo.setInterfaceType(ThirdInterfaceType.MAPGOO_QUERY_TERMINAL_REGISTER.getValue());
            interfaceBo.setAccessUrl(url);
            interfaceBo.setRequestType("POST");
            interfaceBo.setRequestBody(JSON.toJSONString(params));
            interfaceBo.setResponseBody(result);

            if (!thirdInterfaceService.insertByBo(interfaceBo)) {
                throw new LinkException("录入接口数据失败");
            }
            log.info("[麦谷接口][查询终端注册结果][保存记录完成]");

            ThirdMapgooR r = JSON.parseObject(result, ThirdMapgooR.class);
            if (r.isSuccess() || r.getCode() == ThirdMapgooR.SUCCESS) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            throw new LinkException(e.getMessage());
        }
    }

    /**
     * 查询最新轨迹
     *
     * @param imei IMEI 号码
     * @return 结果
     */
    @Override
    public GisTimePosistionVo queryTerminalPosition(String orderId, String imei) {

        try {
            log.info("[麦谷接口][查询最新轨迹][开始]");
            BaseThirdInterfaceConfigVo config = baseThirdInterfaceConfigService.getInterfaceConfig(ThirdInterfaceType.MAPGOO_QUERY_TERMINAL_POSITION.getValue());

            String url = config.getAccessUrl();
            log.info("[麦谷接口][查询最新轨迹][请求地址]: {}", url);

            Map<String, Object> params = new HashMap<>();
            params.put("terminalId", imei);
            log.info("[麦谷接口][查询最新轨迹][请求内容]: {}", JSON.toJSONString(params));

            String result = HttpClientUtil.post(url, JSON.toJSONString(params), false);
            log.info("[麦谷接口][查询最新轨迹][返回内容]: {}", result);

            BaseThirdInterfaceBo interfaceBo = new BaseThirdInterfaceBo();
            interfaceBo.setBusinessId(orderId);
            interfaceBo.setInterfaceType(ThirdInterfaceType.MAPGOO_QUERY_TERMINAL_POSITION.getValue());
            interfaceBo.setAccessUrl(url);
            interfaceBo.setRequestType("POST");
            interfaceBo.setRequestBody(JSON.toJSONString(params));
            interfaceBo.setResponseBody(result);

            if (!thirdInterfaceService.insertByBo(interfaceBo)) {
                throw new LinkException("录入接口数据失败");
            }
            log.info("[麦谷接口][查询最新轨迹][保存记录完成]");

            ThirdMapgooR<DistributeDevicePosisitionVo> r = JSON.parseObject(result, new TypeReference<ThirdMapgooR<DistributeDevicePosisitionVo>>() {});
            if (r.isSuccess() || r.getCode() == ThirdMapgooR.SUCCESS) {
                if (r.getData() == null) {
                    GisTimePosistionVo gisTimePosistionVo = new GisTimePosistionVo();
                    gisTimePosistionVo.setLatitude(new BigDecimal(20.01339));
                    gisTimePosistionVo.setLongitude(new BigDecimal(110.310566));
                    gisTimePosistionVo.setSendTime(LocalDateTime.parse("2024-10-24 18:09:14.000", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
                    return gisTimePosistionVo;
                } else {
                    DistributeDevicePosisitionVo vo = r.getData();
                    interfaceBo.setResponseData(JSON.toJSONString(vo));
                    if (!thirdInterfaceService.updateByBo(interfaceBo)) {
                        log.error("[发行接口][查询终端][更新三方记录失败] {}", interfaceBo);
                        throw new LinkException("更新三方记录失败");
                    }

                    GisTimePosistionVo gisTimePosistionVo = new GisTimePosistionVo();
                    if (StrUtil.isNotBlank(vo.getSendTime())) {
                        gisTimePosistionVo.setLatitude(new BigDecimal(vo.getLatitude()));
                    } else {
                        gisTimePosistionVo.setLatitude(new BigDecimal(20.01339));
                    }
                    if (StrUtil.isNotBlank(vo.getLongitude())) {
                        gisTimePosistionVo.setLongitude(new BigDecimal(vo.getLongitude()));
                    } else {
                        gisTimePosistionVo.setLongitude(new BigDecimal(110.310566));
                    }
                    if (StrUtil.isNotBlank(vo.getSendTime())) {
                        gisTimePosistionVo.setSendTime(LocalDateTime.parse(vo.getSendTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
                    } else {
                        gisTimePosistionVo.setSendTime(LocalDateTime.parse("2024-10-24 18:09:14.000", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
                    }
                    return gisTimePosistionVo;
                }
            } else {
                throw new LinkException(r.getMsg());
            }
        } catch (Exception e) {
            throw new LinkException(e.getMessage());
        }
    }

    /**
     * 同步备案数据
     *
     * @param imei IMEI 号码
     * @return 结果
     */
    @Override
    public boolean syncTerminalFilingData(String orderId, String imei) {
        try {
            log.info("[麦谷接口][同步备案数据][开始]");
            BaseThirdInterfaceConfigVo config = baseThirdInterfaceConfigService.getInterfaceConfig(ThirdInterfaceType.MAPGOO_SYNC_TERMINAL_FILING.getValue());

            String url = config.getAccessUrl();
            log.info("[麦谷接口][同步备案数据][请求地址]: {}", url);

            Map<String, Object> params = new HashMap<>();
            params.put("terminalId", imei);
            log.info("[麦谷接口][同步备案数据][请求内容]: {}", JSON.toJSONString(params));

            String result = HttpClientUtil.post(url, JSON.toJSONString(params), false);
            log.info("[麦谷接口][同步备案数据][返回内容]: {}", result);

            BaseThirdInterfaceBo interfaceBo = new BaseThirdInterfaceBo();
            interfaceBo.setBusinessId(orderId);
            interfaceBo.setInterfaceType(ThirdInterfaceType.MAPGOO_SYNC_TERMINAL_FILING.getValue());
            interfaceBo.setAccessUrl(url);
            interfaceBo.setRequestType("POST");
            interfaceBo.setRequestBody(JSON.toJSONString(params));
            interfaceBo.setResponseBody(result);

            if (!thirdInterfaceService.insertByBo(interfaceBo)) {
                throw new LinkException("录入接口数据失败");
            }
            log.info("[麦谷接口][同步备案数据][保存记录完成]");

            ThirdMapgooR r = JSON.parseObject(result, ThirdMapgooR.class);
            if (r.isSuccess() || r.getCode() == ThirdMapgooR.SUCCESS) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            throw new LinkException(e.getMessage());
        }
    }

    /**
     * 查询激活状态
     *
     * @param imei IMEI 号码
     * @return 结果
     */
    @Override
    public DistributeDeviceActiveVo queryTerminalActive(String orderId, String imei) {
        try {
            log.info("[麦谷接口][查询激活状态][开始]");
            BaseThirdInterfaceConfigVo config = baseThirdInterfaceConfigService.getInterfaceConfig(ThirdInterfaceType.MAPGOO_QUERY_TERMINAL_ACTIVE.getValue());

            String url = config.getAccessUrl();
            log.info("[麦谷接口][查询激活状态][请求地址]: {}", url);

            Map<String, Object> params = new HashMap<>();
            params.put("terminalId", imei);
            log.info("[麦谷接口][查询激活状态][请求内容]: {}", JSON.toJSONString(params));

            String result = HttpClientUtil.post(url, JSON.toJSONString(params), false);
            log.info("[麦谷接口][查询激活状态][返回内容]: {}", result);

            BaseThirdInterfaceBo interfaceBo = new BaseThirdInterfaceBo();
            interfaceBo.setBusinessId(orderId);
            interfaceBo.setInterfaceType(ThirdInterfaceType.MAPGOO_QUERY_TERMINAL_ACTIVE.getValue());
            interfaceBo.setAccessUrl(url);
            interfaceBo.setRequestType("POST");
            interfaceBo.setRequestBody(JSON.toJSONString(params));
            interfaceBo.setResponseBody(result);

            if (!thirdInterfaceService.insertByBo(interfaceBo)) {
                throw new LinkException("录入接口数据失败");
            }
            log.info("[麦谷接口][查询激活状态][保存记录完成]");

            ThirdMapgooR<DistributeDeviceActiveVo> r = JSON.parseObject(result, ThirdMapgooR.class);
            if (r.isSuccess() || r.getCode() == ThirdMapgooR.SUCCESS) {
                DistributeDeviceActiveVo vo = r.getData();
                interfaceBo.setResponseData(JSON.toJSONString(vo));
                if (!thirdInterfaceService.updateByBo(interfaceBo)) {
                    log.error("[发行接口][查询终端][更新三方记录失败] {}", interfaceBo);
                    throw new LinkException("更新三方记录失败");
                }

                try {
                    remoteInstallOrderService.deviceActive(
                        imei,
                        vo.getActiveTime(),
                        vo.getFirstOnlineTime(),
                        interfaceBo.getId()
                    );
                    log.info("[发行接口][检测终端信息][激活完成]");
                } catch (Exception e) {
                    log.error("[发行接口][检测终端信息][激活完成]", e);
                }
                return vo;
            } else {
                throw new LinkException(r.getMsg());
            }
        } catch (Exception e) {
            throw new LinkException(e.getMessage());
        }
    }
}
